﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model;
using BLL;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using Common;


namespace WebPortal.Controllers
{
    public class HomeController : BaseController
    {
        public ActionResult Index()
        {
            //if (Session["MDM_UserName"] == null || Request.Cookies["MDM_UserName"] == null)
            //    return RedirectToAction("LogOn", "Account");
            return View();
        }

        public ActionResult AddPortal()
        {
            return View();
        }
        public ActionResult GetDBInfo()
        {
            return View();
        }
        /// <summary>
        /// 数据库属性
        /// </summary>
        /// <param name="dbName">数据库名</param>
        /// <returns></returns>
        public ActionResult DBInfo(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            DataTable dt = bll.GetDataTable(string.Format("select * from GetDataBaseInfo('{0}')", dbName));
            string data = "执行成功！";
            if (dt != null && dt.Rows.Count > 0)
                data = SysPublicBLL.DataTableToString(dt, 0, "", "", false, true, false);
            return Json(data);
        }
        /// <summary>
        /// 收缩数据库
        /// </summary>
        /// <param name="dbName">数据库名</param>
        /// <returns></returns>
        public ActionResult SHRINKDATABASE(string dbName)
        {
            try
            {
                LoginInfo loginInfos = base.loginInfo();
                SysPublicBLL bll = new SysPublicBLL(loginInfos);
                bll.GetDataTable(string.Format("DBCC SHRINKDATABASE('{0}')", dbName));
                //string data = SysPublicBLL.DataTableToString(dt, 0, "", "", true);

                return Json("DBCC 执行完毕。如果 DBCC 输出了错误信息，请与系统管理员联系。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 数据库重新生成索引
        /// </summary>
        /// <param name="dbName">数据库名</param>
        /// <returns></returns>
        public ActionResult DBREINDEX(string dbName)
        {
            try
            {
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                SysPublicBLL bll = new SysPublicBLL(loginInfos);
                bll.GetDataTable("exec sp_msforeachtable 'DBCC DBREINDEX(''?'')'");
                return Json("DBCC 执行完毕。如果 DBCC 输出了错误信息，请与系统管理员联系。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="oldPwd">原密码</param>
        /// <param name="pwd">新密码</param>
        /// <returns></returns>
        public ActionResult ChangePassword(string oldPwd, string pwd)
        {
            if (Request.Cookies["MDM_UserName"] == null)
                return Json("请重新登录。");
            else
            {
                try
                {
                    string userName = Request.Cookies["MDM_UserName"].Value;
                    return Json(SysUserBLL.ChangePassword(userName, pwd, oldPwd));
                }
                catch (Exception ex)
                {
                    return Json(ex.Message);
                }
            }
        }
        /// <summary>
        /// 对接系统名称和code信息
        /// </summary>
        /// <returns></returns>
        public ActionResult TargetSysName(string dbName)
        {
            string name = "superadmin";
            LoginInfo loginInfos = base.loginInfo();
            loginInfos.DBName = dbName;
            EtlTargetSystemBLL bll = new EtlTargetSystemBLL(loginInfos);
            IList<EtlTargetSystemInfo> data = new List<EtlTargetSystemInfo>();
            DataTable dt = bll.GetDBInfo(new SqlParameter[] { new SqlParameter("@username", name) });
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    data.Add(new EtlTargetSystemInfo() { TargetSysCode = row["TargetSysCode"].ToString(), TargetSysName = row["TargetSysName"].ToString() });
                }
            }

            return Json(data);
        }
        /// <summary>
        /// 切换对接系统
        /// </summary>
        /// <param name="code">对接系统编码</param>
        /// <returns></returns>
        [HttpPost]
        public string ChangeCode(string code, string dbName)
        {
            if (!string.IsNullOrEmpty(code))
            {
                LoginInfo loginInfos = base.loginInfo();
                loginInfos.DBName = dbName;
                EtlTargetSystemBLL bll = new EtlTargetSystemBLL(loginInfos);
                var model = bll.GetList(code);//根据对接系统code得到对接系统信息
                this.Response.Cookies.Add(new HttpCookie("MDM_DBUser", model.DB_UserID));
                this.Response.Cookies.Add(new HttpCookie("MDM_DBPwd", model.DB_PWD));
                this.Response.Cookies.Add(new HttpCookie("MDM_TargetType", model.TargetType.ToString()));
                this.Response.Cookies.Add(new HttpCookie("MDM_TargetCode", code));
                this.Response.Cookies.Add(new HttpCookie("MDM_dbName", dbName));
            }
            return "OK";
        }
        /// <summary>
        /// 删除实例
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult DropDataBase(string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            try
            {
                if (Session["MDM_UserName"] != null && Request.Cookies["MDM_UserName"] != null)
                {
                    if (dbName == "MDM_Platform")
                        return Json("该实例不可删除！");
                    else
                    {
                        if (bll.DropDataBase(dbName))
                        {
                            string etlPath = Server.MapPath("/Deploy/ETL_Package/" + dbName);
                            if (System.IO.Directory.Exists(etlPath))
                                System.IO.Directory.Delete(etlPath, true);//删除etl文件
                            new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功,
                   "删除实例操作,操作成功,实例名=" + dbName, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                            return Json("删除成功！");
                        }
                        else
                            new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.失败,
                  "删除实例操作,操作失败,实例名=" + dbName, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");
                        return Json("删除失败！");
                    }
                }
                else
                    return Json("删除失败！您没有删除实例的权限，或请重新登录后重试。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 禁用实例
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult StopDataBase(string status, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            try
            {
                if (Session["MDM_UserName"] != null && Request.Cookies["MDM_UserName"] != null)
                {
                    if (dbName == "MDM_Platform_2_0")
                        return Json("该实例不可禁用！");
                    else
                    {
                        string dbStatus = status == "禁用" ? "2" : "1";
                        if (bll.UpDataBaseStatus(dbStatus, dbName))
                        {
                            new SysOperationLog(loginInfos).Log("菜单管理", Request.UserHostAddress, OperationAction.删除, OperationStatus.成功,
                      "删除实例操作,操作成功,实例名=" + dbName, Request.Cookies["MDM_UserName"] != null ? Request.Cookies["MDM_UserName"].Value : "");

                            return Json(status + "成功！");
                        }
                        else
                            return Json(status + "失败！");
                    }
                }
                else
                    return Json("禁用失败！登录超时或您没有禁用实例的权限，或请重新登录后重试。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 断开实例
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public ActionResult DisConnectDB(string status, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            try
            {
                if (Session["MDM_UserName"] != null && Request.Cookies["MDM_UserName"] != null)
                {
                    string dbStatus = status == "断开" ? "1" : "0";
                    if (bll.ConnectDB(dbStatus, Request.Cookies["MDM_UserName"].Value, dbName))
                        return Json(status + "成功！");
                    else
                        return Json(status + "失败！");
                }
                else
                    return Json("操作失败！登录超时或您没有禁用实例的权限，或请重新登录后重试。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        /// <summary>
        /// 启用停止任务
        /// </summary> 
        /// <returns></returns>
        public ActionResult DBJob(string status, string dbName)
        {
            LoginInfo loginInfos = base.loginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            try
            {
                if (Session["MDM_UserName"] != null && Request.Cookies["MDM_UserName"] != null)
                {
                    string dbStatus = status == "停止任务" ? "0" : "1";
                    if (bll.DBJob(dbStatus, dbName))
                        return Json(status + "成功！");
                    else
                        return Json(status + "失败！");
                }
                else
                    return Json("操作失败！登录超时或您没有禁用实例的权限，或请重新登录后重试。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
        public ActionResult CreateDataBase(string a, string b, string c, string d, string dbType)
        {
            List<string> msg = new List<string>();
            try
            {
                LoginInfo loginInfos = base.loginInfo();
                SysPublicBLL bll = new SysPublicBLL(loginInfos);
                string dataBase = ConfigurationManager.AppSettings["DataBase"].ToString();
                int dbCount = bll.ExistDB(a, true);
                if (dbCount == 0)
                {
                    string dbName = Guid.NewGuid().ToString().Replace("-", "");
                    if (a.ToLower() == dataBase.ToLower())//为基础实例创建etl
                    {
                        msg.Add(CreateETL(dataBase));
                        msg.Add(CreateJob(dataBase, "1"));
                    }
                    else
                    {
                        //string dbPath = Server.MapPath(c);
                        //string BackUpFilePath = Server.MapPath(d);
                        if (bll.CreateDB(dbName, a, b, c, d, dbType))
                            msg.Add("创建数据库成功！");
                        else
                            msg.Add("创建数据库失败！");
                        msg.Add(CreateETL(dbName));
                        msg.Add(CreateJob(dbName, dbType));
                    }
                    return Json(msg);
                }
                else
                {
                    return Json("存在相同的实例名称，请重新录入！");
                }
            }
            catch (Exception ex)
            {
                msg.Add(ex.Message);
                return Json(msg);
            }
        }
        public string CreateETL(string db)
        {
            try
            {
                string etlPath = Server.MapPath("/Deploy/ETL_Package/");
                CopyFiles(etlPath + "Package", etlPath + db);
                string dataBase = ConfigurationManager.AppSettings["DataBase"].ToString();
                string connectionSetting = ConfigurationManager.ConnectionStrings["ConnectionSetting"].ToString();
                connectionSetting = connectionSetting.Replace(dataBase, db);
                //修改BCP_Proces文件夹下配置
                string BCPFoder = etlPath + db + "\\BCP_Process";
                string[] BCPFiles = System.IO.Directory.GetFiles(BCPFoder);
                foreach (string file in BCPFiles)
                {
                    if (file.LastIndexOf(".config") > 0)
                    {
                        string BCPConfig = System.IO.File.ReadAllText(file);
                        System.IO.File.WriteAllText(file, BCPConfig.Replace("{0}", connectionSetting).Replace("{1}", BCPFoder));
                    }
                }
                //修改ETL文件配置
                string ETLFoder = etlPath + db + "\\Wanda_MDM_Platform_ETL_2_0\\Wanda_MDM_Platform_ETL";
                string[] ETLFiles = System.IO.Directory.GetFiles(ETLFoder);
                foreach (string file in ETLFiles)
                {
                    if (file.LastIndexOf(".dtsConfig") > 0)
                    {
                        string ETLConfig = System.IO.File.ReadAllText(file);
                        System.IO.File.WriteAllText(file, ETLConfig.Replace("{0}", connectionSetting).Replace("{bcp}", BCPFoder));
                    }
                    if (file.LastIndexOf(".dtsx") > 0)
                    {
                        string ETLConfig = System.IO.File.ReadAllText(file);
                        System.IO.File.WriteAllText(file, ETLConfig.Replace("{0}", connectionSetting).Replace("{1}", ETLFoder).Replace("{bcp}", BCPFoder));
                    }
                }

                LoginInfo loginInfos = base.loginInfo();
                SysPublicBLL bll = new SysPublicBLL(loginInfos);
                bll.ModifyModel(ETLFoder);
                return "部署ETL包成功！";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        private void CopyFiles(string sourFoder, string desFoder)
        {
            if (!Directory.Exists(desFoder))
            {
                System.IO.Directory.CreateDirectory(desFoder);
            }
            string[] files = System.IO.Directory.GetFiles(sourFoder);
            foreach (string s in files)
            {
                string destFile = Path.Combine(desFoder, Path.GetFileName(s));
                System.IO.File.Copy(s, destFile, false);
            }
            string[] dirs = System.IO.Directory.GetDirectories(sourFoder);
            foreach (string d in dirs)
            {
                CopyFiles(d, desFoder + d.Replace(sourFoder, ""));
            }
        }
        public string CreateJob(string db, string dbType)
        {
            try
            {
                string etlPath = Server.MapPath("/Deploy/ETL_Package/");
                string modelFoder = etlPath + db + "\\Wanda_MDM_Platform_ETL_2_0\\Wanda_MDM_Platform_ETL\\";

                string jobTemp = "";
                if (dbType == "1")
                    jobTemp = System.IO.File.ReadAllText(etlPath + "JobTemp.sql");
                else
                    jobTemp = System.IO.File.ReadAllText(etlPath + "bigdateJobTemp.sql");

                string sql = jobTemp.Replace("{0}", db).Replace("{1}", modelFoder);

                LoginInfo loginInfos = base.loginInfo();
                SysPublicBLL bll = new SysPublicBLL(loginInfos);
                bll.CreateJob(sql);
                return "操作成功！";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 重命名实例名称
        /// </summary> 
        /// <returns></returns>
        public ActionResult RenameDB()
        {
            string dbName = Request.Params["dbName"];
            string newDBName = Request.Params["newDBName"];
            LoginInfo loginInfos = base.loginInfo();
            SysPublicBLL bll = new SysPublicBLL(loginInfos);
            try
            {
                if (Session["MDM_UserName"] != null && Request.Cookies["MDM_UserName"] != null)
                {
                    string dataBase = ConfigurationManager.AppSettings["DataBase"].ToString();
                    int dbCount = bll.ExistDB(newDBName, true);
                    if (dbCount == 0)
                    {
                        if (bll.RenameDB(dbName, newDBName))
                        {
                            return Json("1");
                        }
                        else
                            return Json("更新失败！");
                    }
                    else
                        return Json("更新失败！存在相同的实例名称，请重新录入！");

                }
                else
                    return Json("更新失败！您没有更新实例的权限，或请重新登录后重试。");
            }
            catch (Exception ex)
            {
                return Json(ex.Message);
            }
        }
    }
}
